package com.bobo.serviceorder.service.impl;

import com.bobo.serviceorder.service.GrabService;
import com.bobo.serviceorder.service.OrderService;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author bobo
 * @date 2021-04-14
 */
@Service
public class GrabRedissonLockServiceImpl implements GrabService {

    @Autowired
    private Redisson redisson;

    @Autowired
    private OrderService orderService;

    @Override
    public String grabOrder(int orderId, int driverId) {
        String lockKey = "lock_" + orderId;
        RLock lock = redisson.getLock(lockKey.intern());
        lock.lock();
        try {
            TimeUnit.SECONDS.sleep(60);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        boolean b = orderService.grabOrder(orderId, driverId);
        if (b) {
            System.out.println("枪单成功！-----");
        } else {
            System.out.println("枪单失败！------");
        }
        lock.unlock();
        return b ? "枪单成功" : "枪单失败";
    }
}
